# -*- coding: utf-8 -*-
from odoo import models,fields
from odoo.exceptions import UserError,ValidationError
from odoo.addons import decimal_precision as dp
from io import BytesIO
import xlwt
import base64
import logging
import logging

_logger = logging.getLogger(__name__)

class ImportQuotationWizard(models.TransientModel):
    _name = 'import.quotation.wizard'
    _inherit = 'import.excel.wizard'
    _description = '导入向导'

    HEARDER_ROW = 0  # 标题的行号
    COLUMN_MAP = {
        '产品件号': 'default_code',
        '数量': 'qty'
    }
    #验证导入的第一列描述存在否
    def _validate_data(self, rownum, data):
        default_code=data.get('default_code').upper()
        if not default_code:
            return
        product_obj = self.env['product.product']
        product = product_obj.search(['|',('default_code', 'ilike', default_code),('default_code2','ilike',default_code)], limit=1)
        if not product:
            self.row_error_info.append(default_code)

    def _format_data(self, field_name, value):
        if isinstance(value, str):
            value = value.strip()
        else:
            value = str(value)      
        return value

    #导入前的处理接口（覆盖源文件import_excel_wizard.py中的方法）
    def _before_process_row_data(self, book, sheet):
        pass
        # self.env['sale.order.line'].search([]).unlink()

    # 导入操作 （覆盖源文件import_excel_wizard.py中的方法）
    def _process_row_data(self, rownum, data):
        data['order_id'] = self._context.get('order_id')
        default_code=data.get('default_code').upper()
        qty=float(data.get('qty',1))
        if not default_code:
            return
        product_id=self.env['product.product'].search(['|',('default_code','ilike',default_code),('default_code2','ilike',default_code)],limit=1)
        data['product_id']=product_id.id
        #报价数量取按起订量与报价单数量的最大值
        if product_id.seller_ids:
            minqty=max(product_id.seller_ids.mapped('min_qty'))
            qty=max(qty,minqty)
        data['product_uom_qty']=qty
        self.env['sale.order.line'].create(data)

    # 导入后的操作 （覆盖源文件import_excel_wizard.py中的方法）
    def _after_process_row_data(self, book, sheet):
        pass
        # sale_order_line_wizard=self.env['sale.order.line.wizard'].search([])
        # erro_data=[]
        #
        # for s in sale_order_line_wizard:
        #     prdt = self.env['product.product'].search([('default_code','ilike',s.default_code)])
        #     if prdt:
        #         self.env['sale.order.line'].create({
        #             'order_id':s.order_id.id,
        #             'product_id':prdt.id
        #         })
        #     else:
        #         erro_data.append(s.default_code)
        # if erro_data:
        #     self._process_errors(erro_data)

    def _process_errors(self, error_messages): #覆盖抽象类中的方法，将错误信息导出到excel。抽象类的方法只是显示错误信息
        if not error_messages:
            return
        wbk = xlwt.Workbook()
        sheet = wbk.add_sheet('Sheet1', cell_overwrite_ok=True)
        sheet.col(0).width = 12000
        for i, rownum in enumerate(error_messages):
            sheet.write(i, 0, error_messages[rownum][0])
        content = BytesIO()
        wbk.save(content)
        content.seek(0)
        out_file = base64.encodestring(content.read())
        self.write({'error_file': out_file, 'error_filename': '不存在产品.xls'})
